const Article = require('../../models/system/article');

// 新增文章
exports.addArticle = async (req, res, next) => {
  try {
    await Article.create(req.body)
    res.send({
      code: 200,
      msg: '操作成功'
    })
  } catch (error) {
    next(error)
  }
}

// 查询文章列表
exports.queryArticleList = async (req, res, next) => {
  try {
    const { page, pageSize, labelType } = req.query;
    let type = labelType?labelType:''
    const article = await Article.find({labelType:type}).skip(pageSize*(page-1)).limit(pageSize).sort({_id: -1});
    const count = await Article.countDocuments({});
    let total = Math.ceil(Number(article.length) / Number(pageSize));
    res.send({
      code: 200,
      msg: '查询成功',
      data: {
        list: article,
        count,
        total
      }
    })
  } catch (error) {
    next(error)
  }
}

// 文章详情
exports.articleDetail = async (req, res, next) => {
  try {
    const { id } = req.query;
    const article = await Article.findById({_id: id});
    if(!article){
      return res.send({
        code: 1001,
        msg: '参数错误',
        data: null
      })
    }
    res.send({
      code: 200,
      msg: '成功',
      data:{
        article
      }
    })
  } catch (error) {
    next(error)
  }
}

// 修改文章
exports.editArticle = async (req, res, next) => {
  try {
    const { id } = req.body;
    await Article.findOneAndUpdate({_id: id}, req.body)
    res.send({
      code: 200,
      msg: '修改成功'
    })
  } catch (error) {
    next(error)
  }
}

// 删除文章
exports.deleteArticle = async (req, res, next) => {
  try {
    const { id } = req.params;
    const article = await Article.deleteOne({_id: id});
    if(!article){
      return res.status(404).send({
        code: 1001,
        msg: '参数错误',
        data: null
      })
    }
    res.send({
      code: 200,
      msg: '删除成功',
    })
  } catch (error) {
    next(error)
  }
}
